package controllers

import (
	"fmt"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"goravel/app/models"
	"goravel/app/services"
	"goravel/app/types"
)

type MenuController struct {
}

func NewMenuController() *MenuController {
	return &MenuController{}
}

// Index 菜单列表
// @Summary      菜单列表
// @Tags         Menu
// @Router       /menu [get]
func (c *MenuController) Index(ctx http.Context) http.Response {
	parentId := ctx.Request().QueryInt("parent_id", 0)
	var err error
	var menus []types.SysMenuListResp
	menuService := services.NewMenuService()
	menus, err = menuService.GetChildren(parentId, 4)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).Data(menus)
}

// Show 菜单详情
// @Summary      菜单详情
// @Tags         Menu
// @Router       /menu/{id} [get]
func (c *MenuController) Show(ctx http.Context) http.Response {
	var model models.SysMenu
	id := ctx.Request().RouteInt("id")
	err := facades.Orm().Query().FindOrFail(&model, id)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).Data(model)
}

// Store 新增菜单
// @Summary      新增菜单
// @Tags         Menu
// @Router       /menu [post]
func (c *MenuController) Store(ctx http.Context) http.Response {
	var createReq types.SysMenuCreateReq
	var err error
	var model models.SysMenu
	err = ctx.Request().Bind(&createReq)
	if err != nil {
		return services.NewApiService(ctx).Error500("参数Bind错误")
	}
	validateErr, err := services.NewApiService(ctx).Validate(&createReq)
	if err != nil {
		return services.NewApiService(ctx).Error500("参数验证错误", services.WithErrors(validateErr))
	}
	err = services.NewMenuService().Create(&model, &createReq)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).OK("stored")
}

// Update 更新菜单
// @Summary      更新菜单
// @Tags         Menu
// @Router       /menu/{id} [put]
func (c *MenuController) Update(ctx http.Context) http.Response {
	id := ctx.Request().RouteInt64("id")
	var updateReq types.SysMenuUpdateReq
	var err error
	var model models.SysMenu
	err = ctx.Request().Bind(&updateReq)
	if err != nil {
		return services.NewApiService(ctx).Error500("参数错误")
	}
	err = services.NewMenuService().Update(&model, &updateReq, id)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).OK("updated")
}

// Destroy 删除菜单
// @Summary      删除菜单
// @Tags         Menu
// @Router       /menu/{id} [delete]
func (c *MenuController) Destroy(ctx http.Context) http.Response {
	id := ctx.Request().RouteInt64("id")
	var err error
	var dao models.SysMenu
	fmt.Println(id)
	err = services.NewMenuService().Delete(&dao, id)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).OK("deleted")
}
